{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Provider ID</th>\n",
       "      <th>Hospital Name</th>\n",
       "      <th>Address</th>\n",
       "      <th>City</th>\n",
       "      <th>State</th>\n",
       "      <th>ZIP Code</th>\n",
       "      <th>County Name</th>\n",
       "      <th>Phone Number</th>\n",
       "      <th>Measure Name</th>\n",
       "      <th>Measure ID</th>\n",
       "      <th>Score</th>\n",
       "      <th>Footnote</th>\n",
       "      <th>Measure Start Date</th>\n",
       "      <th>Measure End Date</th>\n",
       "      <th>Location</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>10005</td>\n",
       "      <td>MARSHALL MEDICAL CENTER SOUTH</td>\n",
       "      <td>2505 U S HIGHWAY 431 NORTH</td>\n",
       "      <td>BOAZ</td>\n",
       "      <td>AL</td>\n",
       "      <td>35957</td>\n",
       "      <td>MARSHALL</td>\n",
       "      <td>2565938310</td>\n",
       "      <td>Medicare hospital spending per patient (Medica...</td>\n",
       "      <td>MSPB_1</td>\n",
       "      <td>0.98</td>\n",
       "      <td>NaN</td>\n",
       "      <td>01/01/2014</td>\n",
       "      <td>12/31/2014</td>\n",
       "      <td>2505 U S HIGHWAY 431 NORTH\\nBOAZ, AL 35957\\n</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>10032</td>\n",
       "      <td>WEDOWEE HOSPITAL</td>\n",
       "      <td>209 NORTH MAIN STREET</td>\n",
       "      <td>WEDOWEE</td>\n",
       "      <td>AL</td>\n",
       "      <td>36278</td>\n",
       "      <td>RANDOLPH</td>\n",
       "      <td>2563572111</td>\n",
       "      <td>Medicare hospital spending per patient (Medica...</td>\n",
       "      <td>MSPB_1</td>\n",
       "      <td>0.84</td>\n",
       "      <td>NaN</td>\n",
       "      <td>01/01/2014</td>\n",
       "      <td>12/31/2014</td>\n",
       "      <td>209 NORTH MAIN STREET\\nWEDOWEE, AL 36278\\n</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Provider ID</th>\n",
       "      <th>Hospital Name</th>\n",
       "      <th>Address</th>\n",
       "      <th>City</th>\n",
       "      <th>State</th>\n",
       "      <th>ZIP Code</th>\n",
       "      <th>County Name</th>\n",
       "      <th>Phone Number</th>\n",
       "      <th>Measure Name</th>\n",
       "      <th>Measure ID</th>\n",
       "      <th>Score</th>\n",
       "      <th>Footnote</th>\n",
       "      <th>Measure Start Date</th>\n",
       "      <th>Measure End Date</th>\n",
       "      <th>Location</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>10005</td>\n",
       "      <td>MARSHALL MEDICAL CENTER SOUTH</td>\n",
       "      <td>2505 U S HIGHWAY 431 NORTH</td>\n",
       "      <td>BOAZ</td>\n",
       "      <td>AL</td>\n",
       "      <td>35957</td>\n",
       "      <td>MARSHALL</td>\n",
       "      <td>2565938310</td>\n",
       "      <td>Medicare hospital spending per patient (Medica...</td>\n",
       "      <td>MSPB_1</td>\n",
       "      <td>0.98</td>\n",
       "      <td>NaN</td>\n",
       "      <td>01/01/2014</td>\n",
       "      <td>12/31/2014</td>\n",
       "      <td>2505 U S HIGHWAY 431 NORTH\\nBOAZ, AL 35957\\n</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>10032</td>\n",
       "      <td>WEDOWEE HOSPITAL</td>\n",
       "      <td>209 NORTH MAIN STREET</td>\n",
       "      <td>WEDOWEE</td>\n",
       "      <td>AL</td>\n",
       "      <td>36278</td>\n",
       "      <td>RANDOLPH</td>\n",
       "      <td>2563572111</td>\n",
       "      <td>Medicare hospital spending per patient (Medica...</td>\n",
       "      <td>MSPB_1</td>\n",
       "      <td>0.84</td>\n",
       "      <td>NaN</td>\n",
       "      <td>01/01/2014</td>\n",
       "      <td>12/31/2014</td>\n",
       "      <td>209 NORTH MAIN STREET\\nWEDOWEE, AL 36278\\n</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 运行该代码可以简单观察数据集\n",
    "import pandas as pd\n",
    "medicare = pd.read_csv('data/medicare.csv')\n",
    "medicare.head(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python基础"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# python 格言\n",
    "#import this"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print('hello world')  # 打印 'hello world!'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "### 1.1 基本语法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = 1 # 变量命名\n",
    "print(x) # 打印变量的值\n",
    "print(type(x))# 查看变量类型\n",
    "x = 'boya'# 之所以成为动态语言的原因\n",
    "print(x)\n",
    "print(type(x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#?ab,2ab,_ab # 变量命名规则，大小写敏感\n",
    "import keyword# 关键字\n",
    "print(keyword.kwlist)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 注释和多行注释"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 数学运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "print(x + 1,x - 1, x * 2,x/2, x ** 2 # 数学运算，加减乘除幂运算\n",
    "# x+=1? x*=2?\n",
    "# x++ ++x?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Python 2与Python 3除法的区别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(1/2)# python 2\n",
    "from __future__ import division # python 3\n",
    "print(1/2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 数据类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2505 U S HIGHWAY 431 NORTH\nBOAZ, AL 35957\n\n"
     ]
    }
   ],
   "source": [
    "# 读取数据集中的\n",
    "import pandas as pd\n",
    "medicare = pd.read_csv('data/medicare.csv')\n",
    "location = medicare['Location'][0]\n",
    "print(location)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 整型、浮点型\n",
    "location # 字符串 location"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(location)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "t = True # 布尔型\n",
    "f = False\n",
    "print(t and f) # 与\n",
    "print(t or f)# 或\n",
    "print(not t)# 非\n",
    "print(t != f)# 异或"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "not (True | False) | True # not (True | False) | True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 字符串类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "S = 'Boyabigdata'\n",
    "print(len(S))# 长度\n",
    "print(S[0])# 索引，顺序和逆序\n",
    "print(S[-2])\n",
    "print(S[:])# 切片\n",
    "print(S[1:3])\n",
    "print(S+'xyz')# 合并和重复\n",
    "print(S*3)\n",
    "raws = r'B\\nya'# 原始字符串\n",
    "print(raws)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "S[0] = 'A'# 更改字符"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 字符串的相关方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "print(S.find('Boya') )# 找到第一次出现'Boya'的位置\n",
    "print(S.replace('Boya','XYZ') )# 替换字符串\n",
    "print(S.upper() )# 大写\n",
    "line='aa,bb,ccc,dd' \n",
    "print(line.split(',')) # 分割\n",
    "line='aa,bb,ccc,dd\\n' \n",
    "print(line.rstrip())# 去掉首尾的\n",
    "print('  world '.strip()) # 去掉首尾的空格\n",
    "hw12='%s %s %d' % ('hello','world',12) #格式化字符串\n",
    "print('{} {} {}'.format('hello','world',12))\n",
    "print(hw12)\n",
    "print(hw12.capitalize())# 首字母大写"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 数据类型相互转换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# int(),float(),bool(),str() "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 文件读写"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "f = open('./data/medicare.csv',mode=\"r\")# 生成文件对象\n",
    "f.read(8)# 三种读取数据的方法read,readline,relines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "f.readline()# readline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "f.readlines()# readlines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "f.seek(0)# 返回文件初始位置seek\n",
    "f.readline()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "f.close()# 关闭文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 读取第一行存为columns,第二行为sample\n",
    "f = open('./data/medicare.csv',mode=\"r\")# 生成文件对象\n",
    "columns = f.readline() # 变量赋值\n",
    "sample = f.readline()\n",
    "f.close()# 关闭文件\n",
    "print(columns)\n",
    "print(sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import csv# csv模块读写\n",
    "f = open('./data/medicare.csv',mode=\"r\")\n",
    "content = csv.reader(f)\n",
    "samples = list(content)\n",
    "print(samples[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# pandas模块读写\n",
    "import pandas as pd\n",
    "medicare = pd.read_csv('./data/medicare.csv')\n",
    "medicare.head(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 提取第一个医院样本\n",
    "f = open('./data/medicare.csv', mode=\"r\") \n",
    "columns = f.readline()\n",
    "sample = f.readline()\n",
    "f.close()\n",
    "clean_sample = sample.strip().split(',')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(type(clean_sample))# 查看类型\n",
    "print(clean_sample)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 列表创建和列表索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sample = ['1325','City Hospital',0.67]\n",
    "print(len(sample))# 列表长度\n",
    "print(sample[0])# 列表索引\n",
    "sample.append('01/01/2014')# 添加列表元素：末尾添加\n",
    "print(sample)\n",
    "sample.insert(-1,'12/31/2014')# 添加列表元素：指定位置添加\n",
    "print(sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sample = ['1325','City Hospital',0.67]\n",
    "date = ['01/01/2014','12/31/2014']\n",
    "# 整合两个列表\n",
    "sample.extend(date)\n",
    "print(sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sample.index(0.67)# 获取元素的索引号"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 练习：提取第一个样本的Hospital Name和Score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 参考代码\n",
    "\n",
    "# 读取数据文件，并进行数据清洗\n",
    "f = open('./data/medicare.csv', mode=\"r\")\n",
    "columns = f.readline()\n",
    "sample = f.readline()\n",
    "f.close()\n",
    "columns_list = columns.strip().split(',')\n",
    "sample_list = sample.strip().split(',')\n",
    "\n",
    "# 使用中间变量index的方法\n",
    "hospital = ['Hospital Name']\n",
    "index = columns_list.index('Hospital Name')\n",
    "hospital.append(sample_list[index])\n",
    "\n",
    "# 不使用中间变量index的方法，节省代码行数，牺牲可读性\n",
    "score = ['Score']\n",
    "score.append(float(sample_list[columns_list.index('Score')]))\n",
    "\n",
    "shortinfo = hospital + score\n",
    "print(shortinfo)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 列表切片和元素删除"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shortinfo = ['Hospital Name', 'MARSHALL MEDICAL CENTER SOUTH', 'Score', 0.98]\n",
    "print(shortinfo[1:3])# 列表切片\n",
    "print(shortinfo[:]) # 拷贝列表\n",
    "print(shortinfo[:2])# 从头开始切片\n",
    "print(shortinfo[::-1])# 切片产生逆序,等价于reverse()，区别？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 字符串切片\n",
    "s = 'cookdata'\n",
    "print(s[2:4])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shortinfo = ['Hospital Name', 'MARSHALL MEDICAL CENTER SOUTH', 'Score', 0.98]\n",
    "shortinfo.remove('MARSHALL MEDICAL CENTER SOUTH') # 元素删除：remove方法\n",
    "print(shortinfo)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shortinfo = ['Hospital Name', 'MARSHALL MEDICAL CENTER SOUTH', 'Score', 0.98]\n",
    "del shortinfo[1] # 元素删除：del方法\n",
    "print(shortinfo)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shortinfo = ['Hospital Name', 'MARSHALL MEDICAL CENTER SOUTH', 'Score', 0.98]\n",
    "shortinfo.pop(1) # 元素删除：pop方法\n",
    "print(shortinfo)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "\" \".join(['c','o','o','k'])# 列表元素连接为字符串,任何列表都可以吗？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 可变数据结构的浅拷贝与深拷贝"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 赋值操作\n",
    "name1 = ['cook']\n",
    "name2 = name1 \n",
    "name1.append('data')\n",
    "print(name1)\n",
    "print(name2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 浅拷贝操作\n",
    "name1 = ['cook',['da','ta']]\n",
    "name2 = name1[:] \n",
    "name2[0] = 'cool'\n",
    "name2[1][0] = 'do'\n",
    "print(name1)\n",
    "print(name2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 深拷贝操作\n",
    "from copy import deepcopy\n",
    "name1 = ['cook',['da','ta']]\n",
    "name2 = deepcopy(name1) \n",
    "name2[0] = 'cool'\n",
    "name2[1][0] = 'do'\n",
    "print(name1)\n",
    "print(name2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.4 控制结构"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "for item in shortinfo:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 循环时改变迭代列表\n",
    "for item in shortinfo[:]:\n",
    "    shortinfo.append(1)\n",
    "print(shortinfo)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# range函数\n",
    "l = ['cook','data']\n",
    "for index in range(len(l)):\n",
    "    print(index, l[index])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# enumerate函数\n",
    "for index, item in enumerate(l):\n",
    "    print(index, item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# zip函数\n",
    "for index, item in zip(range(len(l)),l):\n",
    "    print(index, item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "false_values = [False,None,0,(),{},[],''] # Python的False值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# if 条件语句\n",
    "review_sentiment = -1\n",
    "if review_sentiment > 0 :   \n",
    "    print('positive')\n",
    "elif review_sentiment ==0:\n",
    "    print('neutral')\n",
    "else: \n",
    "    print('negative')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# while 循环结构\n",
    "review_sentiment = -1\n",
    "while review_sentiment < 5:  \n",
    "    review_sentiment += 1\n",
    "    print('review_sentiment equals %d' % review_sentiment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# break,continue,pass\n",
    "review_sentiment = -1\n",
    "while review_sentiment < 20:  \n",
    "    review_sentiment += 1\n",
    "    print('review_sentiment equals %d' % review_sentiment)\n",
    "    if review_sentiment > 1:\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 练习：取出Hospital Name和Score，并将Hospital每个单词转换为首字母大写"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import csv\n",
    "with open('./input/medicare.csv', mode=\"r\") as f:\n",
    "    content = csv.reader(f)\n",
    "    samples = list(content)\n",
    "\n",
    "# 找到两列的索引位置\n",
    "idx1 = samples[0].index('Hospital Name')\n",
    "idx2 = samples[0].index('Score')\n",
    "samples_filtered = []\n",
    "\n",
    "# 将Hospital Name中的单词转换为首字母大写的形式\n",
    "for item in samples[1:]:\n",
    "    words = item[idx1].strip().split(\" \")\n",
    "    for index,word in enumerate(words):\n",
    "        words[index] = word.capitalize()\n",
    "    item[idx1] = \" \".join(words)\n",
    "    samples_filtered.append([item[idx1],item[idx2]])\n",
    "print(samples_filtered[:3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.5 元组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shortinfo_tuple = tuple(shortinfo) # 元素不可变\n",
    "print(shortinfo_tuple)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shortinfo_tuple.count('Score')# 元素个数统计"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shortinfo_tuple.index(0.98)# 返回索引位置"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.6 字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "samples_filtered[:2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 创建字典的三种方式\n",
    "dict1 = {'Marshall Medical Center South':0.98,'Wedowee Hospital':0.84}\n",
    "dict2 = dict(Marshall_Medical_Center_South=0.98,Wedowee_Hospital=0.84)\n",
    "dict3 = dict([('Marshall Medical Center South',0.98),('Wedowee Hospital',0.84)])\n",
    "\n",
    "dict4 = dict([('Wedowee Hospital',0.84),('Marshall Medical Center South',0.98)]) # 无序性"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(dict1)\n",
    "print(dict2)\n",
    "print(dict3)\n",
    "print(dict4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# 有序字典\n",
    "from collections import OrderedDict\n",
    "ordered_dict1 = OrderedDict([('Wedowee Hospital',0.84),('Marshall Medical Center South',0.98)])\n",
    "ordered_dict2 = OrderedDict([('Marshall Medical Center South',0.98),('Wedowee Hospital',0.84)])\n",
    "print(ordered_dict1)\n",
    "print(ordered_dict2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 通过两个列表创建字典\n",
    "key_list = ['Marshall Medical Center South','Wedowee Hospital']\n",
    "value_list = [0.98,0.84]\n",
    "dict5 = {}\n",
    "for key, value in zip(key_list,value_list):\n",
    "    dict5[key] = value\n",
    "print(dict5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 元素访问\n",
    "\n",
    "print(dict5['Marshall Medical Center South'] )# 通过键直接访问\n",
    "print(dict5.get('Marshall Medical Center South')) # get方法获得键的值\n",
    "print(dict5.get('Marshall') )# 不存在键值，返回none\n",
    "print(dict5.get('Marshall',u'键值不存在')) # 可以指定键不存在时，返回的值\n",
    "print('Marshall Medical Center South' in dict5) # in 查询\n",
    "print(dict5.has_key('Marshall') )# has_key 查询"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(dict5.keys() )# 返回所有的键\n",
    "print(dict5.values()) # 返回所有的值\n",
    "print(dict5.items())# 返回键值元组列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "for key,value in dict5.items(): # items遍历读取字典键值\n",
    "    print(key,\":\",value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "dict5['City Hospital']= 1 # 字典元素的添加 \n",
    "print(dict5)\n",
    "del dict5['Wedowee Hospital'] # del方法删除字典元素\n",
    "print(dict5 )\n",
    "dict5.pop('City Hospital') # pop方法删除元素\n",
    "print(dict5)\n",
    "dict5.clear() # 删除字典中所有元素\n",
    "print(dict5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.7 集合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "set1 = {1,2,3}# {}创建集合\n",
    "print(set1)\n",
    "print(shortinfo )# set函数创建集合\n",
    "shortinfo_set = set(shortinfo)\n",
    "print(shortinfo_set)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shortinfo_set.add('City Hospital') # 增加元素\n",
    "print(shortinfo_set)\n",
    "shortinfo_set.remove('City Hospital') # 删除元素\n",
    "print(shortinfo_set)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "shortinfo_set # 并集、交集、差集等集合运算"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.8 推导式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "列表推导式，集合推导式，字典推导式 \n",
    "\n",
    "想想为什么没有元组推导式？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# 把列表shortinfo中的所有元素变为字符串(多行)\n",
    "for index,item in enumerate(shortinfo):\n",
    "    shortinfo[index] = str(item)\n",
    "print(shortinfo)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 列表推导式\n",
    "[str(item) for item in shortinfo]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "key_list = ['Marshall Medical Center South','Wedowee Hospital']\n",
    "value_list = [0.98,0.84]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "{str(item) for item in set(shortinfo)}# 集合推导式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 通过两个列表创建字典\n",
    "dict5 = {}\n",
    "for key, value in zip(key_list,value_list):\n",
    "    dict5[key] = value\n",
    "print(dict5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 字典推导式\n",
    "{key:value for key,value in zip(key_list,value_list)}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.9 函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 定义平方函数\n",
    "def square(x):\n",
    "    s = x*x\n",
    "    return s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "square(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### lambda函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "square = lambda x:x*x# 快速定义函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### map函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "map(square,range(5)) # 列表中的元素依次执行函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "print([item.capitalize() for item in columns_list]\n",
    "print(map(lambda x:x.capitalize(),columns_list))# map与lambda结合的优雅方式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.10 模块导入"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# import module as alias\n",
    "# from module import *\n",
    "# from module import func1,fun2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.11 类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 定义欢迎用户的类\n",
    "class Greeter(object):\n",
    "    \n",
    "    # 构造方法\n",
    "    def __init__(self, name):\n",
    "        self.name = name  # 创建一个实例变量\n",
    "        \n",
    "    # 实例方法\n",
    "    def greet(self, upper=False):\n",
    "        if upper:\n",
    "            print('HELLO, %s!' % self.name.upper())\n",
    "        else:\n",
    "            print('Hello, %s' % self.name)\n",
    "        \n",
    "g = Greeter('Fred')  # 创建Greeter类的一个实例\n",
    "g.greet()            # 调用实例方法，使用默认参数\n",
    "g.greet(upper=True)   # 调用实例方法，自定义参数"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
